package com.lingnan.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lingnan.dto.CompanyAuditDTO;
import com.lingnan.dto.CompanyAuditRequest;
import com.lingnan.dto.CompanyQueryRequest;
import com.lingnan.entity.dto.CompanyVerificationRequest;
import com.lingnan.entity.po.Company;
import com.lingnan.entity.po.UserAccount;
import com.lingnan.entity.vo.Result;
import com.lingnan.feign.NotificationFeignClient;
import com.lingnan.mapper.CompanyMapper;
import com.lingnan.mapper.UserAccountMapper;
import com.lingnan.service.CompanyAuditService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Slf4j
@Service
@RequiredArgsConstructor
public class CompanyAuditServiceImpl implements CompanyAuditService {
    
    private final CompanyMapper companyMapper;
    private final UserAccountMapper userAccountMapper;
    private final NotificationFeignClient notificationFeignClient;

    /**
     * 获取企业审核列表
     * @param query
     * @return
     */
    @Override
    public Result<IPage<CompanyAuditDTO>> getCompanyAuditList(CompanyQueryRequest query) {
        try {
            Page<CompanyAuditDTO> page = new Page<>(query.getCurrent()==null?1l:query.getCurrent(), query.getSize()==null?10:query.getSize());
            IPage<CompanyAuditDTO> result = companyMapper.selectCompanyAuditPage(page, query);
            return Result.ok(result);
        } catch (Exception e) {
            log.error("查询企业审核列表失败", e);
            return Result.fail("查询企业审核列表失败");
        }
    }

    /**
     * 企业审核
     * @param request
     * @param adminId
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Result<Void> auditCompany(CompanyAuditRequest request, Long adminId) {
        try {
            // 检查企业是否存在
            Company company = companyMapper.selectById(request.getCompanyId());
            if (company == null) {
                return Result.fail("企业不存在");
            }
            
            // 检查企业状态是否为待审核
            if (!company.getStatus().equals(0)) {
                return Result.fail("企业已审核，无法重复审核");
            }
            
            // 更新企业审核状态
            UpdateWrapper<Company> updateWrapper = new UpdateWrapper<>();
            updateWrapper.eq("id", request.getCompanyId())
                        .set("status", request.getStatus())
                        .set("update_id", adminId);
            
            int updateResult = companyMapper.update(null, updateWrapper);
            if (updateResult <= 0) {
                return Result.fail("审核失败");
            }
            
            // 如果审核通过，更新关联用户账号状态为启用
            if (request.getStatus().equals(1)) {
                UpdateWrapper<UserAccount> userUpdateWrapper = new UpdateWrapper<>();
                userUpdateWrapper.eq("id", company.getUserId())
                               .set("status", 1);
                userAccountMapper.update(null, userUpdateWrapper);
            }

            log.info("企业审核成功，企业ID：{}，审核状态：{}，审核人：{}", 
                    request.getCompanyId(), request.getStatus(), adminId);

            // 发送企业审核结果通知
            sendNotification(request, adminId, company);
            return Result.ok();
            
        } catch (Exception e) {
            log.error("审核企业失败", e);
            return Result.fail("审核企业失败");
        }
    }


@Async
public void sendNotification(CompanyAuditRequest request, Long adminId, Company company) {
    try {
        log.info("发送企业审核结果通知，企业ID：{}，审核状态：{}，审核人：{}", company.getId(), request.getStatus(), adminId);
        CompanyVerificationRequest verificationRequest = new CompanyVerificationRequest();
        verificationRequest.setReceiverId(company.getUserId());
        verificationRequest.setCompanyName(company.getName());
        verificationRequest.setApproved(request.getStatus().equals(1));
        verificationRequest.setReason(request.getReason());
        notificationFeignClient.sendCompanyVerificationResult(verificationRequest);
    } catch (Exception e) {
        log.error("发送企业审核结果通知失败", e);
    }
}


    /**
     * 获取企业详情
     * @param companyId
     * @return
     */
    @Override
    public Result<CompanyAuditDTO> getCompanyDetail(Long companyId) {
        try {
            // 查询企业信息
            Company company = companyMapper.selectById(companyId);
            if (company == null) {
                return Result.fail("企业不存在");
            }
            
            // 查询关联用户信息
            UserAccount userAccount = userAccountMapper.selectById(company.getUserId());
            
            // 构建返回对象
            CompanyAuditDTO dto = new CompanyAuditDTO();
            dto.setId(company.getId());
            dto.setUserId(company.getUserId());
            dto.setCompanyName(company.getName());
            dto.setLicenseNo(company.getLicenseNo());
            dto.setLicenseImg(company.getLicenseImg());
            dto.setIndustry(company.getIndustry());
            dto.setScale(company.getScale());
            dto.setAddress(company.getAddress());
            dto.setWebsite(company.getWebsite());
            dto.setStatus(company.getStatus());
            dto.setCreatedAt(company.getCreatedAt());
            
            if (userAccount != null) {
                dto.setUsername(userAccount.getUsername());
                dto.setNickName(userAccount.getNickName());
                dto.setEmail(userAccount.getEmail());
                dto.setPhone(userAccount.getPhone());
            }
            
            return Result.ok(dto);
            
        } catch (Exception e) {
            log.error("获取企业详情失败", e);
            return Result.fail("获取企业详情失败");
        }
    }
}